<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { OrderStateEnum, orderStateList } from '@/services/constants'
import { getMemberOrderAPI, mockPayAPI, getPayParamsAPI } from '@/services/order'
import type { OrderItem, OrderListParams } from '@/types/order'
import PageSkeleton from './PageSkeleton.vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const props = defineProps<{
  orderState: OrderStateEnum
}>()

const orderList = ref<OrderItem[]>([])
const page = ref(1)
const pages = ref(0)

/**获取订单列表 */
const getOrderList = async (data: OrderListParams) => {
  const res = await getMemberOrderAPI(data)
  page.value = res.result.page
  pages.value = res.result.pages
  orderList.value.push(...res.result.items)
}

/**监听滚动条到达底部事件 */
const onScrollToLower = async () => {
  if (page.value >= pages.value) return (isLoadAll.value = true)
  page.value++
  await getOrderList({
    page: page.value,
    pageSize: 10,
    orderState: props.orderState,
  })
}

/**是否为开发环境 */
const isDEV = import.meta.env.DEV

/**支付 */
const handlePay = async (order: OrderItem) => {
  // 判断是否是开发环境
  if (isDEV) {
    await mockPayAPI(order.id)
  } else {
    // #ifdef MP-WEIXIN
    const res = await getPayParamsAPI(order.id)
    wx.requestPayment(res.result)
    // #endif
  }
  uni.showToast({ title: '支付成功' })
  orderList.value.find((item) => item.id === order.id)!.orderState = OrderStateEnum.WAIT_DELIVER
}

// 是否显示完数据-用于骨架屏
const isLoad = ref(false)

//是否加载完全部数据-用于触底滚动样式显示
const isLoadAll = ref(false)

onMounted(() => {
  Promise.all([
    getOrderList({
      page: 1,
      pageSize: 10,
      orderState: props.orderState,
    }),
  ]).finally(() => {
    isLoad.value = true
  })
})
</script>

<template>
  <!-- 订单列表 -->
  <scroll-view v-if="isLoad" scroll-y class="orders" @scrolltolower="onScrollToLower">
    <view class="card" v-for="item in orderList" :key="item.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ item.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[item.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text
          class="icon-delete"
          v-if="
            [
              OrderStateEnum.CANCELED,
              OrderStateEnum.FINISHED,
              OrderStateEnum.WAIT_EVALUATE,
            ].includes(item.orderState)
          "
        ></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
        v-for="sku in item.skus"
        :key="sku.id"
        class="goods"
        :url="`/pagesOrder/detail/detail?id=${sku.id}`"
        hover-class="none"
      >
        <view class="cover">
          <image mode="aspectFit" :src="sku.image"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ sku.name }}</view>
          <view class="type">{{ sku.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ item.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ item.payMoney }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="item.orderState === OrderStateEnum.WAIT_PAYMENT">
          <view class="button primary" @click="handlePay(item)">去支付</view>
        </template>
        <template v-else>
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${item.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view v-if="item.orderState === OrderStateEnum.WAIT_RECEIVE" class="button primary"
            >确认收货</view
          >
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ isLoadAll ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
  <PageSkeleton v-else />
</template>

<style scoped></style>
